package com.woniuxy.service.impl;

import com.woniuxy.dao.OrderDao;
import com.woniuxy.entity.Order;
import com.woniuxy.entity.Product;
import com.woniuxy.entity.utils.ResponseEntity;
import com.woniuxy.service.OrderService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.RestTemplate;

import java.util.Map;


//@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderDao orderDao;

    @Override
    public ResponseEntity generateOrder(Integer pid, Integer num) {
        //使用入门的微服务调用方案
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity productResp = restTemplate.getForObject("http://localhost:8081/products/" + pid, ResponseEntity.class);

        //判断是否获取到数据
        if (Integer.parseInt(productResp.get(ResponseEntity.ResponseStatus.CODE.value()) + "") == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
            return productResp;
        }

        //把LinkedHashMap转换成Product对象
        Map map = (Map) productResp.get(ResponseEntity.ResponseStatus.DATA.value());
        Product product = new Product();
        try {
            BeanUtils.populate(product, map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //User封装
        Order order = new Order();
        order.setUid(1);
        order.setUsername("Dadd");
        order.setPid(product.getPid());
        order.setPname(product.getName());
        order.setPrice(product.getPrice());
        //存储购买数量
        order.setNumber(num);

        Order returnOrder = null;
        //判断是否订单入库
        if (product.getStock() - num >= 0) { //成功，扣减
            returnOrder = orderDao.save(order);
            product.setStock(product.getStock() - num);
            restTemplate.put("http://localhost:8081/products/", product);
        }else { //失败，返回消息
            return new ResponseEntity(HttpStatus.NOT_MODIFIED.value(), "商品卖完了。");
        }

        return new ResponseEntity(returnOrder);
    }
}
